package de.jmda.mview.proj;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;

import javax.lang.model.element.TypeElement;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

import org.apache.log4j.Logger;

public class TypesTreeTypeElementPopup implements ActionListener
{
	private final static Logger LOGGER =
      Logger.getLogger(TypesTreeTypeElementPopup.class);

	/**
	 * Enumerates the menu items for the popup.
	 */
	private enum Items
	{
		ADD("add"),
		;

		private String name;

		private Items(String name)
		{
			this.name = name;
		}
	}

	/**
	 * event that represents the tree node click
	 */
	private TypesTreeNodeClicked typesTreeNodeClicked;

	/**
	 * type element of the clicked tree node
	 */
	private TypeElement typeElement;

	/**
	 * shortcut to {@link TypesTreeNodeClicked#getDiagramsController()}
	 */
	private DiagramsController diagramsController;
	
	/**
	 * shortcut to {@link TypesTreeNodeClicked#getMouseEvent()}
	 */
	private MouseEvent mouseEvent;

	private JPopupMenu menu;

	/**
	 * @param typesTreeNodeClicked
	 * @param typeElement
	 */
	public TypesTreeTypeElementPopup(
			TypesTreeNodeClicked typesTreeNodeClicked, TypeElement typeElement)
	{
		super();

		this.typesTreeNodeClicked = typesTreeNodeClicked;
		this.typeElement = typeElement;
		
		diagramsController = typesTreeNodeClicked.getDiagramsController();
		mouseEvent = typesTreeNodeClicked.getMouseEvent();
		
		menu = initialiseMenu();
	}

	private JPopupMenu initialiseMenu()
  {
		menu = new JPopupMenu();

		if (diagramsController.displayOptionAddTypeElement(typeElement))
		{
			JMenuItem itemAddTypeElement = new JMenuItem(Items.ADD.name);
			itemAddTypeElement.addActionListener(this);
			menu.add(itemAddTypeElement);
		}
		
		return menu;
  }

	public void run()
	{
		menu.show(mouseEvent.getComponent(), mouseEvent.getX(), mouseEvent.getY());
	}

	@Override
	public void actionPerformed(ActionEvent actionEvent)
	{
		if (actionEvent.getActionCommand().equals(Items.ADD.name))
		{
			addTypeElement();
		}
		else
		{
			LOGGER.warn(
					"unexpected action event with action command " +
					actionEvent.getActionCommand());
		}
	}

	private void addTypeElement()
  {
		diagramsController.addTypeElement(typeElement);
  }
}